from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from api import models


class QueryParamsAuthentication(BaseAuthentication):
    def authenticate(self, request):
        # 获取用户认证，读取token
        # 三种返回值1.返回元组 2.返回异常 3.返回None->匿名用户
        # token = request._request.GET("token")
        token = request.query_params.get("token")
        if not token:
            return
        user_object = models.UserInfo.objects.filter(token=token).first()

        if user_object:
            return user_object, token

        return

    def authenticate_header(self, request):
        return "API"


class HeaderAuthentication(BaseAuthentication):
    def authenticate(self, request):
        # 获取用户认证，读取token
        # 三种返回值1.返回元组 2.返回异常 3.返回None->匿名用户
        # token = request._request.GET("token")
        token = request.META.get("HTTP_AUTHORIZATION")
        if not token:
            return
        user_object = models.UserInfo.objects.filter(token=token).first()

        if user_object:
            return user_object, token

        return

    def authenticate_header(self, request):
        return "API"


class NoAuthentication(BaseAuthentication):
    def authenticate(self, request):
        raise AuthenticationFailed({"status":False,"msg":"认证失败"})

    def authenticate_header(self, request):
        return "API"
